<?php

namespace App\Services;

use App\Models\Dish;
use App\Models\Room;
use App\Models\Menu;
use App\Models\Category;
use Illuminate\Support\Collection;

class DishService
{
    /**
     * 获取所有菜品（分页）
     */
    public function getDishes(int $perPage = 20)
    {
        return Dish::with(['category', 'creator', 'menu.rooms'])
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    /**
     * 根据筛选条件获取菜品
     */
    public function getDishesByFilters(array $filters, int $perPage = 20)
    {
        $query = Dish::with(['category', 'creator', 'menu.rooms']);

        if (!empty($filters['category_id'])) {
            $query->where('category_id', $filters['category_id']);
        }

        if (isset($filters['is_featured'])) {
            $query->where('is_featured', $filters['is_featured']);
        }

        if (!empty($filters['search'])) {
            $search = $filters['search'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        return $query->orderBy('created_at', 'desc')->paginate($perPage);
    }

    /**
     * 获取菜品统计信息
     */
    public function getDishStats(): array
    {
        return [
            'total' => Dish::count(),
            'system' => Dish::where('dish_source', 'system')->count(),
            'user' => Dish::where('dish_source', 'user')->count(),
            'menu' => Dish::where('dish_source', 'menu')->count(),
            'featured' => Dish::where('is_featured', true)->count(),
            'available' => Dish::where('is_available', true)->count(),
        ];
    }

    /**
     * 根据分类获取菜品
     */
    public function getDishesByCategory(int $categoryId, int $perPage = 20)
    {
        return Dish::with(['category', 'creator', 'menu.rooms'])
            ->where('category_id', $categoryId)
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    /**
     * 根据ID获取菜品
     */
    public function getDishById(int $dishId): Dish
    {
        return Dish::with(['category', 'creator', 'menu.rooms'])->findOrFail($dishId);
    }

    /**
     * 更新菜品
     */
    public function updateDish(int $dishId, array $data): Dish
    {
        $dish = Dish::findOrFail($dishId);
        
        // 处理标签和口味字段：将逗号分隔的字符串转换为数组
        if (isset($data['tags']) && is_string($data['tags'])) {
            $data['tags'] = array_filter(array_map('trim', explode(',', $data['tags'])));
        }
        if (isset($data['flavors']) && is_string($data['flavors'])) {
            $data['flavors'] = array_filter(array_map('trim', explode(',', $data['flavors'])));
        }
        
        $dish->update($data);
        
        return $dish->fresh(['category', 'creator', 'menu.rooms']);
    }

    /**
     * 切换菜品推荐状态
     */
    public function toggleDishFeatured(int $dishId): Dish
    {
        $dish = Dish::findOrFail($dishId);
        $dish->is_featured = !$dish->is_featured;
        $dish->save();

        return $dish;
    }

    /**
     * 为菜单初始化菜品（根据菜单来源复制菜品）
     */
    public function initializeMenuDishes(Menu $menu): void
    {
        switch ($menu->source_type) {
            case 'default':
                // 复制默认菜单的菜品
                $this->copyDefaultMenuDishes($menu);
                break;
            case 'custom':
                // 自定义菜单：如果是其他用户的菜单，需要复制菜品
                $this->copyCustomMenuDishes($menu);
                break;
            default:
                // 如果是新建菜单，不复制任何菜品
                break;
        }
    }

    /**
     * 复制默认菜单菜品
     */
    private function copyDefaultMenuDishes(Menu $menu): void
    {
        // 获取默认菜单的菜品（这里需要根据实际业务逻辑来定义什么是"默认菜单"）
        // 可能是系统预设的推荐菜品，或者特定分类的菜品
        $defaultDishes = Dish::system()
            ->available()
            ->where('is_featured', true) // 假设默认菜单是推荐菜品
            ->get();

        foreach ($defaultDishes as $dish) {
            $this->copyDishToMenu($dish, $menu, $menu->creator_id);
        }
    }


    /**
     * 复制自定义菜单菜品
     */
    private function copyCustomMenuDishes(Menu $menu): void
    {
        if (!$menu->source_id) {
            return;
        }

        $sourceMenu = Menu::find($menu->source_id);
        if (!$sourceMenu) {
            return;
        }

        // 如果是其他用户的菜单，需要复制菜品
        if ($sourceMenu->creator_id !== $menu->creator_id) {
            $sourceDishes = $sourceMenu->dishes()->available()->get();
            foreach ($sourceDishes as $dish) {
                $this->copyDishToMenu($dish, $menu, $menu->creator_id);
            }
        }
        // 如果是自己的菜单，直接关联即可，不需要复制
    }

    /**
     * 为菜单添加自定义菜品
     */
    public function addCustomDishToMenu(Menu $menu, array $dishData, int $creatorId): Dish
    {
        return Dish::create([
            'name' => $dishData['name'],
            'description' => $dishData['description'] ?? null,
            'category_id' => $dishData['category_id'] ?? null,
            'creator_id' => $creatorId,
            'menu_id' => $menu->id,
            'source_dish_id' => null, // 自定义菜品不关联系统菜品
            'dish_source' => 'menu',
            'is_public' => false,
            'image' => $dishData['image'] ?? null,
            'tags' => $dishData['tags'] ?? [],
            'flavors' => $dishData['flavors'] ?? [],
            'cooking_time' => $dishData['cooking_time'] ?? null,
            'is_available' => $dishData['is_available'] ?? true,
            'is_featured' => $dishData['is_featured'] ?? false,
            'sort_order' => $dishData['sort_order'] ?? 0,
        ]);
    }

    /**
     * 获取菜单菜品列表
     */
    public function getMenuDishes(Menu $menu): Collection
    {
        return Dish::byMenu($menu->id)
            ->with(['category', 'creator', 'sourceDish'])
            ->available()
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 修改菜单菜品
     */
    public function updateMenuDish(Dish $dish, array $updateData): Dish
    {
        $dish->update($updateData);
        return $dish->fresh(['category', 'creator', 'sourceDish']);
    }

    /**
     * 删除菜单菜品
     */
    public function deleteMenuDish(Dish $dish): bool
    {
        return $dish->delete();
    }

    /**
     * 获取用户的自定义菜品
     */
    public function getUserCustomDishes(int $userId): Collection
    {
        return Dish::byCreator($userId)
            ->where('dish_source', 'user')
            ->whereNull('menu_id')
            ->with(['category'])
            ->available()
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 创建用户自定义菜品
     */
    public function createUserCustomDish(array $dishData, int $creatorId): Dish
    {
        return Dish::create([
            'name' => $dishData['name'],
            'description' => $dishData['description'] ?? null,
            'category_id' => $dishData['category_id'] ?? null,
            'creator_id' => $creatorId,
            'menu_id' => null,
            'source_dish_id' => null,
            'dish_source' => 'user',
            'is_public' => $dishData['is_public'] ?? false,
            'image' => $dishData['image'] ?? null,
            'tags' => $dishData['tags'] ?? [],
            'flavors' => $dishData['flavors'] ?? [],
            'cooking_time' => $dishData['cooking_time'] ?? null,
            'is_available' => $dishData['is_available'] ?? true,
            'is_featured' => $dishData['is_featured'] ?? false,
            'sort_order' => $dishData['sort_order'] ?? 0,
        ]);
    }

    /**
     * 复制菜品到菜单
     */
    public function copyDishToMenu(Dish $sourceDish, Menu $menu, int $creatorId): Dish
    {
        return Dish::create([
            'name' => $sourceDish->name,
            'description' => $sourceDish->description,
            'category_id' => $sourceDish->category_id,
            'creator_id' => $creatorId,
            'menu_id' => $menu->id,
            'source_dish_id' => $sourceDish->id,
            'dish_source' => 'menu',
            'is_public' => false,
            'image' => $sourceDish->image,
            'tags' => $sourceDish->tags,
            'flavors' => $sourceDish->flavors,
            'cooking_time' => $sourceDish->cooking_time,
            'is_available' => $sourceDish->is_available,
            'is_featured' => $sourceDish->is_featured,
            'sort_order' => $sourceDish->sort_order,
        ]);
    }

    /**
     * 获取公开的用户菜品
     */
    public function getPublicUserDishes(): Collection
    {
        return Dish::user()
            ->public()
            ->available()
            ->with(['category', 'creator'])
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 搜索菜单菜品
     */
    public function searchMenuDishes(Menu $menu, string $keyword = null, int $categoryId = null): Collection
    {
        $query = Dish::byMenu($menu->id)
            ->with(['category', 'creator', 'sourceDish'])
            ->available();

        if ($keyword) {
            $query->search($keyword);
        }

        if ($categoryId) {
            $query->byCategory($categoryId);
        }

        return $query->orderBy('sort_order', 'asc')->orderBy('created_at', 'desc')->get();
    }

    /**
     * 创建菜品
     */
    public function createDish(array $dishData): Dish
    {
        return Dish::create($dishData);
    }
}